<template>
  <div style="display: inline">
    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    />

    <el-button
      :loading="loading"
      style="background-color: #ff9920; color: #fff; height: 36px"
      @click="handleUpload"
    >
      {{ title }}
    </el-button>
    <!-- <excel
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      title="导入"
    /> -->
  </div>
</template>

<script>
import XLSX from "xlsx";

export default {
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function, // eslint-disable-line
    title: {
      require: true,
      type: String,
      default: "导入",
    },
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null,
      },
    };
  },
  methods: {
    // beforeUpload(file) {
    //   const isLt1M = file.size / 1024 / 1024 < 1;

    //   if (isLt1M) {
    //     return true;
    //   }

    //   this.$message({
    //     message: "Please do not upload files larger than 1m in size.",
    //     type: "warning",
    //   });
    //   return false;
    // },
    // formatExcelDate(numb, format = "/") {
    //   const time = new Date(
    //     (numb - 25567) * 24 * 3600000 -
    //       5 * 60 * 1000 -
    //       43 * 1000 -
    //       24 * 3600000 -
    //       8 * 3600000
    //   );
    //   time.setYear(time.getFullYear());
    //   const year = time.getFullYear() + "";
    //   const month = time.getMonth() + 1 + "";
    //   const date = time.getDate() + "";
    //   if (format && format.length === 1) {
    //     return year + format + month + format + date;
    //   }
    //   return (
    //     year +
    //     (month < 10 ? "0" + month : month) +
    //     (date < 10 ? "0" + date : date)
    //   );
    // },
    // /**
    //  * results excel表格的内容
    //   //        [ {'姓名'：'小张'， '手机号': '13712345678'}, {.....} ]
    //   // 目标
    //   //        [ {'username'：'小张'， 'mobile': '13712345678'}, {.....} ]
    //  */
    // transExcel(results) {
    //   const userRelations = {
    //     账号: "accountCode",
    //     姓名: "employeeName",
    //   };
    //   return results.map((item) => {
    //     const obj = {};
    //     // 1. 取出这个对象所有的属性名： ['姓名'， ‘手机号’]
    //     // 2. 遍历这个数组，通过 中文名去 userRelations 找对应英文名， 保存值
    //     const zhKeys = Object.keys(item);
    //     zhKeys.forEach((zhKey) => {
    //       const enKey = userRelations[zhKey];
    //       // 如果是时间格式，就要做转换
    //       if (enKey === "correctionTime" || enKey === "timeOfEntry") {
    //         obj[enKey] = new Date(this.formatExcelDate(item[zhKey]));
    //       } else {
    //         obj[enKey] = item[zhKey];
    //       }
    //     });

    //     return obj;
    //   });
    // },
    // // excel导入
    // handleSuccess({ results, header }) {
    //   console.log(results, header);
    //   const arr = this.transExcel(results);
    //   console.log("转换之后的格式是", arr);
    // },
    generateData({ header, results }) {
      this.excelData.header = header;
      this.excelData.results = results;
      this.onSuccess && this.onSuccess(this.excelData);
    },
    handleUpload() {
      this.$refs["excel-upload-input"].click();
    },
    handleClick(e) {
      const files = e.target.files;
      const rawFile = files[0]; // only use files[0]
      console.log(rawFile);
      if (!rawFile) return;
      this.upload(rawFile);
    },
    upload(rawFile) {
      this.$refs["excel-upload-input"].value = null; // fix can't select the same excel

      if (!this.beforeUpload) {
        this.readerData(rawFile);
        return;
      }
      const before = this.beforeUpload(rawFile);
      if (before) {
        this.readerData(rawFile);
      }
    },
    readerData(rawFile) {
      this.loading = true;
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: "array" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const header = this.getHeaderRow(worksheet);
          const results = XLSX.utils.sheet_to_json(worksheet);
          this.generateData({ header, results });
          this.loading = false;
          resolve();
        };
        reader.readAsArrayBuffer(rawFile);
      });
    },
    getHeaderRow(sheet) {
      const headers = [];
      const range = XLSX.utils.decode_range(sheet["!ref"]);
      let C;
      const R = range.s.r;
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
        /* find the cell in the first row */
        let hdr = "UNKNOWN " + C; // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
        headers.push(hdr);
      }
      return headers;
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name);
    },
  },
};
</script>

<style scoped>
.excel-upload-input {
  display: none;
  z-index: -9999;
}
</style>
